﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
public class UIPanelStateData{
}
public class UIPanelStateMachineData{
}
public class PanelEditor{
	public List<UIPanelStateMachineData> stateMachine = new List<UIPanelStateMachineData>();
	public List<UIPanelStateData> state = new List<UIPanelStateData>();
}
public enum HotEditorType{
	LuaView,
	Scene,
}
public class HotUIEditor : EditorWindow {
	const string editorPath =  "Standard Assets/GameTools/HotUI/Editor/";
	JSON.JSONNode data;
	HotEditorType editorType = HotEditorType.LuaView;
	int createView = -1;
	string createName = "";
	string createPath = "";
	bool repeatName = false;
	bool repeatPath = false;
	string search = "";
	string editorView;
	System.Action create;
	[MenuItem("HotUI/EditorPanel")]
	public static void Init(){
		var win = GetWindow<HotUIEditor> ();
		var data = Resources.Load ("Data/UIFSM") as TextAsset;
		win.data = JSON.JSONNode.Parse (data.text);
	}
	public void OnEnable(){
		if (data == null) {
			data = JSON.JSONNode.Parse((Resources.Load ("Data/UIFSM") as TextAsset).text);
		}
	}
	Vector2 sv;
	public void OnGUI(){
		editorType = (HotEditorType)EditorGUILayout.EnumPopup ((System.Enum)editorType);
		sv = EditorGUILayout.BeginScrollView (sv);
		switch (editorType) {
		case HotEditorType.LuaView:
			if (data != null) {
				repeatName = false;
				repeatPath = false;
				if (createView == -1) {
					search = EditorGUILayout.TextField ("Search", search);
					createName = "";
					createPath = "";
				} else {
					search = "";
				}
				DrawData ("状态机界面", data ["stateMachine"], 0);
				DrawData ("状态/弹出框", data ["state"], 1);
			} else {
			}
			break;
		case HotEditorType.Scene:
			break;
		}
		EditorGUILayout.EndScrollView ();
		Repaint ();
	}
	void DrawStateM(){
		
	}
	bool CheckRepeatName(string name){
		if (name.Equals (createName)) {
			repeatName = true;
			return true;
		}
		return false;
	}
	bool CheckRepeatPath(string path){
		if (path.Equals (path)) {
			repeatPath = true;
			return true;
		}
		return false;
	}
	bool isLikeNameOrPath(string key){
		for (var i = 0; i < data ["stateMachine"].Count; i++) {
			if (key.Equals (data ["stateMachine"] [i] ["name"].ToString ())
				|| key.Equals (data ["stateMachine"] [i] ["path"].ToString ())) {
				return true;
			}
		}
		for (var i = 0; i < data ["state"].Count; i++) {
			if (key.Equals (data ["state"] [i] ["name"].ToString ())
				|| key.Equals (data ["state"] [i] ["path"].ToString ())) {
				return true;
			}
		}
		return false;
	}
	int cachedRemove;
	void LoadView(string name){
		editorView = name;
		var obj = GameObject.Instantiate (Resources.Load ("ViewUI/ui_" + editorView)) as GameObject;
		var uirool = GameObject.FindObjectOfType<UIRoot> ();
		if (uirool == null) {
			var rootobj = GameObject.Instantiate (Resources.Load ("Prefab/UIRoot")) as GameObject;
			uirool = rootobj.GetComponent<UIRoot> ();
		} else {
			obj.transform.parent = uirool.transform;
			obj.transform.localPosition = Vector3.zero;
			obj.transform.localEulerAngles = Vector3.zero;
			obj.transform.localScale = Vector3.one;
		}

		obj.name = "ui_"+editorView;
	}
	void SaveView(){
		var gameobj = GameObject.Find ("ui_" + editorView);
		if (gameobj != null) {
			SavePrefab ("Resources/ViewUI/ui_" + editorView, gameobj);
			GameObject.DestroyImmediate (gameobj);
		}
		editorView = "";
	}

	void SaveUIData(){
		var info = new FileInfo (Application.dataPath + "/Resources/Data/UIFSM.txt");
		if (info.Exists) {
			info.Delete ();
		}
		var sr = info.CreateText ();
		sr.Write (data.ToString ());
		sr.Close ();
		AssetDatabase.Refresh ();
	}

	void ChangeName(string oldname,string newname){
		Debug.Log (oldname + "改成:" + newname);
		oldname = oldname.ToLower ();
		newname = newname.ToLower ();
		ChangeFileName ("lua_ui_" + oldname, "lua_ui_" + newname, ".txt", "Resources/LuaTxt/");
		ChangeFileName ("ui_" + oldname, "ui_" + newname, ".lua", "Resources/Lua/");
		ChangeFileName ("ui_" + oldname, "ui_" + newname, ".prefab", "Resources/ViewUI/");
		AssetDatabase.Refresh ();
	}

	void ChangeFileName(string oldname,string newname,string ex,string path){
		FileInfo file = new FileInfo (Application.dataPath+"/"+path+oldname+ex);
		if (file.Exists) {
			file.CopyTo (Application.dataPath + "/" + path + newname + ex);
			file.Delete ();
		}
	}
	void DrawData(string name,JSON.JSONNode stateData,int type){
		EditorGUILayout.BeginVertical ("box");
		EditorGUILayout.LabelField (name);
		for(var i = 0;i < stateData.Count;i++){
			if (search == "" || stateData [i] ["name"].ToString ().Contains (search) || stateData [i] ["path"].ToString ().Contains (search)) {
				GUILayout.BeginHorizontal ();
				GUI.backgroundColor = CheckRepeatName (stateData [i] ["name"].ToString ()) ? Color.red : Color.white;
				string viewname = stateData [i] ["name"].ToString ();
				string viewpath = stateData [i] ["path"].ToString ();
				GUILayout.Label ("Name", GUILayout.Width (40));
				stateData [i] ["name"] = GUILayout.TextField (stateData [i] ["name"].ToString (), GUILayout.Width (90));
				stateData [i] ["name"] = stateData [i] ["name"].ToString ().ToLower ();
				GUI.backgroundColor = CheckRepeatName (stateData [i] ["path"].ToString ()) ? Color.red : Color.white;
				GUILayout.Label ("path", GUILayout.Width (40));
				stateData [i] ["path"] = GUILayout.TextField (stateData [i] ["path"].ToString ());
				stateData [i] ["path"] = stateData [i] ["path"].ToString ().ToLower ();
				GUI.backgroundColor = Color.red;
				if(viewname != stateData[i]["name"].ToString() && GUI.changed){
					ChangeName (viewname,stateData[i]["name"].ToString());
					viewname = stateData [i] ["name"].ToString ();
					SaveUIData ();
				}
				if (viewpath != stateData [i] ["path"].ToString ()) {
					viewpath = stateData [i] ["path"].ToString ();
					SaveUIData ();
				}
				viewname = stateData [i] ["name"].ToString ();
				if (editorView == viewname) {
					GUI.backgroundColor = Color.green;
					if (GUILayout.Button ("保存", GUILayout.Width (30))) {
						SaveView ();
					}
				} 
				else {
					GUI.backgroundColor = Color.white;
					string path = Application.dataPath + "/Resources/ViewUI/ui_" + viewname+".prefab";
					var fileinfo = new FileInfo (path);
					EditorGUI.BeginDisabledGroup (!fileinfo.Exists);
					if (GUILayout.Button ("加载", GUILayout.Width (30))) {
						LoadView (viewname);
					}
					if (GUILayout.Button ("打开", GUILayout.Width (30))) {
						Application.OpenURL(@"C:\Program Files (x86)\Sublime Text3\sublime_text.exe");
					}
					EditorGUI.EndDisabledGroup ();
				}
				if (GUILayout.Button ("X", GUILayout.Width (30))) {
					cachedRemove = i;
					if (EditorUtility.DisplayDialog ("删除UI", "是否删除名为[" + viewname + "]的界面,该操作无法还原", "删除")) {
						DeleLuaView (viewname);
						stateData.Remove (cachedRemove);
					}
					SaveUIData ();
				}
				GUILayout.EndHorizontal ();
			}
		}
		GUI.backgroundColor = Color.white;
		if (createView == type) {
			GUILayout.Label ("Create");
			string errorInfo = "";
			bool likeName = isLikeNameOrPath(createName);
			bool likePath = isLikeNameOrPath(createPath);
			bool nameError = false;
			bool pathError = false;
			if (type == 0) {
				if (createPath == "") {
					errorInfo += "不允许空路径\n";
					pathError = true;
				}
				if (createName == "") {
					errorInfo += "不允许空名字\n";
					nameError = true;
				}
				if (likeName) {
					errorInfo += "名字重复\n";
					nameError = true;
				}
				if (likePath) {
					errorInfo += "路径重复\n";
					pathError = true;
				}
			}

			GUILayout.BeginHorizontal ();
			GUI.backgroundColor = nameError?Color.red: Color.green;
			GUILayout.Label ("Name", GUILayout.Width (40));
			createName = EditorGUILayout.TextField (createName, GUILayout.Width (90));
			GUI.backgroundColor = pathError?Color.red: Color.green;
			GUILayout.Label ("path", GUILayout.Width (40));
			createPath = EditorGUILayout.TextField (createPath);
			EditorGUI.BeginDisabledGroup (errorInfo != "");
			if (GUILayout.Button ("Add")) {
				if (EditorUtility.DisplayDialog ("创建UI", "是否创建名为[" + createName + "] 路径[" + createPath + "]的界面", "创建")) {
					AddUIState (type, createName, createPath);	
					createView = -1;
					SaveUIData ();
				}
			}
			EditorGUI.EndDisabledGroup ();
			GUILayout.EndHorizontal ();
			GUI.backgroundColor = Color.white;
			if (errorInfo != "") {
				EditorGUILayout.HelpBox (errorInfo, MessageType.Error);
			}
			if (GUILayout.Button ("Cancle",GUILayout.Width(50))) {
				createView = -1;
			}
		} else {
			if (search == "" &&  GUILayout.Button ("Add",GUILayout.Width(50))) {
				createView = type;
			}
		}
		EditorGUILayout.EndVertical ();
	}
	void DeleLuaView(string name){
		DeleFile(Application.dataPath + "/Resources/Lua/ui_"+name+".lua");
		DeleFile(Application.dataPath + "/Resources/LuaTxt/lua_ui_"+name+".txt");
		DeleFile(Application.dataPath + "/Resources/ViewUI/ui_"+name+".prefab");
		AssetDatabase.Refresh ();
	}
	void DeleFile(string path){
		var info = new FileInfo (path);
		if (info.Exists)
			info.Delete ();
	}
	void AddUIState(int type,string name,string path){
		name = name.ToLower ();
		path = path.ToLower ();
		//lua script
		var luaname = "ui_"+name+".lua";
		var target = Application.dataPath + "/Resources/Lua/"+luaname;
		FileInfo fileinfo = new FileInfo (target);
		if (fileinfo.Exists)
			fileinfo.Delete ();
		var sr = fileinfo.CreateText ();
		sr.Write ((LoadTemple<TextAsset> ("templuaview")).text);
		sr.Close ();

		//viewobj
		var obj = LoadTemple<GameObject>("tempobjview",".prefab");
		obj.name = "ui_" + name;
		GameObject newviewobj = GameObject.Instantiate(obj);
		SavePrefab ("Resources/ViewUI/ui_" + name, obj);
		var deleobj = GameObject.Find ("ui_" + name+"(Clone)");
		if (deleobj != null)
			GameObject.DestroyImmediate (deleobj);

		string key = "";
		int count = 0;
		if (type == 0) {
			key = "stateMachine";
		} else {
			key = "state";
		}
		count = data [key].Count;
		data [key] [count] ["name"] = name;
		data [key] [count] ["path"] = path;

		AssetDatabase.Refresh ();
	}

	void SavePrefab(string path,GameObject obj){
		path = "Assets/"+path+ ".prefab";
		PrefabUtility.CreatePrefab(path,obj);
	}
	T LoadTemple<T>(string fileName,string ex = ".txt") where T:Object{
		var path = "Assets/"+editorPath + fileName+ex;
		Debug.Log (path);
		var obj = AssetDatabase.LoadAssetAtPath<T> (path);
		return obj;
	}
}

public class HotUICreate:EditorWindow{
	int type;
	System.Action<int,string,string> callback;
	public static void Init(int _type,System.Action<int,string,string> _callback){
		var win = GetWindow<HotUICreate> ();
		win.type = _type;
		win.callback = _callback;
	}
	string path;
	string name;
	public void OnGUI(){
		name = EditorGUILayout.TextField ("UIName", name);
		path = EditorGUILayout.TextField ("UIPath", path);
		if (GUILayout.Button ("create")) {
			if (EditorUtility.DisplayDialog ("创建UI", "是否创建名为[" + name + "] 路径[" + path + "]的界面", "创建")) {
				callback (type,name, path);
			}
		}
	}
}
